import 'package:flutter/material.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/detail/views/detail_header_topic_view.dart';
import 'package:flutter_douban/main_page/home/notes/home_card_view.dart';
import 'package:flutter_douban/model/active_big_model.dart';
import 'package:flutter_douban/model/topic_model.dart';
import 'package:flutter_douban/tool_views/loading_page.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

const APPBAR_SCROLL_OFFSET = 100; //设置滑动变化的偏移量

class TopicDetailPage extends StatefulWidget {
  final int id;
  const TopicDetailPage({Key? key, required this.id}) : super(key: key);

  @override
  _TopicDetailPageState createState() => _TopicDetailPageState();
}

class _TopicDetailPageState extends State<TopicDetailPage> {
  @override

  /// 下拉刷新控制器
  late EasyRefreshController _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;

  /// 头部数据
  TopicModel? _topicModel;

  /// 列表数组模型
  List<ActiveBigModel> _activeBigList = ActiveBigModelList([]).list;
  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;
  double appBarAlpha = 0;

  /// 监听列表偏移
  _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  /// 获取数据
  Future _getHotDetailData({bool replace = true}) async {
    try {
      /// 全部数据
      Map<String, dynamic> result = await HttpService.getHotDetailData(
          page: page, pageSize: 10, id: widget.id);
      TopicModel topicFirstModel = TopicModel.fromJson(result['topic']);
      /// 列表
      ActiveBigModelList activeBigModelList =
          ActiveBigModelList.fromJson(result['list']);
      setState(() {
        page++;
        if (replace) {
          _topicModel = topicFirstModel;
          _activeBigList = activeBigModelList.list;
        } else {}
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    _onRefresh();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getHotDetailData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getHotDetailData(replace: false);
    }
    // 结束加载
    _easyRefreshController.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    if (_activeBigList.length == 0) {
      return StancePage();
    } else {
      return Scaffold(
        body: Container(
          color: Colors.white,
          child: Stack(
            children: <Widget>[
              MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: NotificationListener(
                    onNotification: (scrollNotification) {
                      if (scrollNotification is ScrollUpdateNotification &&
                          scrollNotification.depth == 0) {
                        //滚动且是列表滚动的时候
                        _onScroll(scrollNotification.metrics.pixels);
                      }
                      return true;
                    },
                    child: EasyRefresh(
                        // 开启首次加载刷新
                        firstRefresh: true,
                        // 加载时的loading
                        firstRefreshWidget: LoadingPage(),
                        // 空视图、异常视图
                        // emptyWidget: PageFeedBack(
                        //   loading: loading,
                        //   error: error,
                        //   empty: _songList.isEmpty,
                        //   errorMsg: errorMsg,
                        //   onErrorTap: () => _easyRefreshController.callRefresh(),
                        //   onEmptyTap: () => _easyRefreshController.callRefresh(),
                        // ).build(),
                        header: CustomHeaderView(),
                        footer: CustomFooterView(),
                        controller: _easyRefreshController,
                        enableControlFinishRefresh: false,
                        enableControlFinishLoad: true,
                        onRefresh: _onRefresh,
                        onLoad: _onLoad,
                        child: Column(
                          children: [
                            HeaderTopicDetailPage(
                              topicModel: _topicModel!,
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                left: 5,
                                right: 5,
                              ),
                              color: Colors.grey[100],
                              child: StaggeredGridView.countBuilder(
                                controller: _scrollController,
                                itemCount: _activeBigList.length,
                                primary: false,
                                shrinkWrap: true,
                                crossAxisCount: 4,
                                mainAxisSpacing: 10.0,
                                crossAxisSpacing: 5.0,
                                itemBuilder: (context, index) => ActiveCardView(
                                  model: _activeBigList[index],
                                ),
                                staggeredTileBuilder: (index) =>
                                    StaggeredTile.fit(2),
                              ),
                            ),
                          ],
                        ))
                ),
              ),
              Opacity(
                opacity: appBarAlpha,
                child: Container(
                  padding: EdgeInsets.only(left: 10, right: 10,top: 30),
                  height: kToolbarHeight + MediaQuery.of(context).padding.top,
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(color: Colors.white),
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Image.asset(
                          'assets/images/common/tab_icon_back.png',
                          width: 20,
                          height: 20,
                        ),
                        Image.asset(
                          'assets/images/common/navi_item_share.png',
                          width: 20,
                          height: 20,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Positioned(
                  bottom: 30,
                  left: (MediaQuery.of(context).size.width - 100) / 2,
                  child: Container(
                    width: 100,
                    height: 36,
                    decoration: BoxDecoration(
                      color: AppColors.yellow,
                      borderRadius: BorderRadius.circular(18),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/common/main_animation_button_icon_black.png',
                          width: 22,
                          height: 22,
                        ),
                        Text(
                          '参与话题',
                          style: TextStyle(
                              fontSize: 12,
                              color: Colors.black,
                              fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                  ))
            ],
          ),
        ),
      );
    }
  }
}
